﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Services;
using System.Web.UI;
using Foothill.Common;
using Foothill.Common.Logging;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service.Configuration;
using Foothill.Service.Session;
using Foothill.Service.SystemMessage;
using Foothill.Service.UploadPhoto;
using AjaxControlToolkit;

namespace Foothill.Web
{
    public partial class PostForSaleUploadPhoto : FoothillBasePage
    {
        private ISessionService _sessionService;
        private IUploadPhotoService _uploadPhotoService;
        private IUploadFileManager _fileManager;
        private ISystemMessageService _systemMessageService;
        private IImageProcessor _imageProcessor;
        private IHostSettingManager _hostSettingManager;

        protected void Page_Load(object sender, EventArgs e)
        {
            _sessionService = IocContainer.GetInstance<ISessionService>();
            _uploadPhotoService = IocContainer.GetInstance<IUploadPhotoService>();
            _fileManager = IocContainer.GetInstance<IUploadFileManager>();
            _systemMessageService = IocContainer.GetInstance<ISystemMessageService>();
            _hostSettingManager = IocContainer.GetInstance<IHostSettingManager>();

            lblUploadPhotoMessage.Visible = false;
            AsyncFileUpload1.UploadedComplete += new EventHandler<AsyncFileUploadEventArgs>(AsyncFileUpload1UploadedComplete);

            if (!IsPostBack)
            {
                _sessionService.ClearSessionVariable(SessionNames.ForSalePhotoList);
                lblNextStepUrl.Text = _hostSettingManager.GetSiteBaseUrlString() + "/PostForSale/PostForSalePreview.aspx";
            }
        }

        [WebMethod]
        public static void DeleteUploadedPhoto(string filenameNoExt)
        {
            if (!string.IsNullOrWhiteSpace(filenameNoExt))
            {
                IList<UploadPhoto> uploadedPhotos = GetUploadedPhotoListFromSession();

                UploadPhoto fileToDelete = uploadedPhotos.FirstOrDefault(p => string.Compare(Path.GetFileNameWithoutExtension(p.PathOnServer), filenameNoExt, true) == 0);

                if (fileToDelete != null)
                {
                    IUploadPhotoService uploadPhotoService = IocContainer.GetInstance<IUploadPhotoService>();

                    try
                    {
                        // delete physical files - photo and thumbnail
                        uploadPhotoService.DeletePhotoAndThumbnail(fileToDelete.PathOnServer, fileToDelete.PathOnServer);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(FoothillModule.View, "Fail to delete a photo from the disk", ex);
                    }

                    uploadedPhotos.Remove(fileToDelete);

                    ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
                    sessionService.SaveSessionValue(SessionNames.ForSalePhotoList, uploadedPhotos);
                }
            }
        }

        [WebMethod]
        public static void Submit(List<string> list)
        {
            IList<UploadPhoto> photoList = GetUploadedPhotoListFromSession();

            foreach (UploadPhoto uploadPhoto in photoList)
            {
                int index = list.FindIndex(x => x.Equals(uploadPhoto.PathOnServer));
                uploadPhoto.DisplayIndex = index;
            }

            ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
            sessionService.SaveSessionValue(SessionNames.ForSalePhotoList, photoList);
        }

        public void AsyncFileUpload1UploadedComplete(object sender, AsyncFileUploadEventArgs e)
        {
            string extension = Path.GetExtension(e.FileName);

            string filename = string.Format("{0}{1}", Guid.NewGuid(), extension);
            string pathOnServer =_uploadPhotoService.GetUploadPhotoPathOnServer(filename);
            _imageProcessor = IocContainer.GetInstance<IImageProcessor>();

            try
            {
                AsyncFileUpload1.SaveAs(pathOnServer);
                _imageProcessor.GenerateThumbnail(GlobalSettings.ThumbnailWidth, GlobalSettings.ThumbnailHeight, pathOnServer);

                UploadPhoto photo = new UploadPhoto
                {
                    PathOnServer = Path.GetFileName(pathOnServer),
                    AdTypeId = (int)AdType.ForSale,
                    UploadDateTime = DateTime.Now
                };

                SaveUploadedPhotoInstanceToSession(photo);
                
                string imageUrl = _uploadPhotoService.GetThumbnailPhotoImageUrl(filename);
                string script = "top.showInTableCell('" + filename + "');";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", script, true);
            }
            catch (Exception ex)
            {
                Log.Error(FoothillModule.View, "Fail to save photo to server "+ e.FileName, ex);
            }          
        }

        // get the photo list from the session
        private static IList<UploadPhoto> GetUploadedPhotoListFromSession()
        {
            List<UploadPhoto> retVal;
            ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
            object obj = sessionService.GetSessionValue(SessionNames.ForSalePhotoList);

            if (obj == null)
            {
                // no photo has been uploaded yet
                retVal = new List<UploadPhoto>();
            }
            else
            {
                retVal = obj as List<UploadPhoto>;
            }

            return retVal;
        }
        
        // add the newly uploaded photo to the list of photos that user has uploaded and save the list of photo objects to session
        private void SaveUploadedPhotoInstanceToSession(UploadPhoto photo)
        {
            IList<UploadPhoto> photoList = GetUploadedPhotoListFromSession();

            int count = photoList.Count;

            if (count >= GlobalSettings.MaxNumOfUploadPhotos)
            {
                return;
            }

            photoList.Add(photo);

            // save the photo list to session
            ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
            _sessionService.SaveSessionValue(SessionNames.ForSalePhotoList, photoList);
        }
    }
}
